import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {PERMISSION} from './constants';
import {PAGE, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import styles from './style.css';
import {Card, Row, Col, Table, Button, Spin, Modal} from 'antd';
import {conventEnumValueToString} from '../utils';
import {workItemStatus} from '../Enum';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
const {Description} = DescriptionList;
import Return from '../common/Return';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import AssistSelectPanel from './AssistSelectPanel';
export class Detail extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        showPanel: false,
        data: {},
        details: [],
    };

    componentDidMount() {
        this.ismounted = true;
        this.setState({loading: true});
        return this.props.init().then(res => {
            if(res.ok) {
                const {assistItems = [], ...props} = res.data;
                this.setState({
                    loading: false,
                    data: {...props},
                    details: assistItems
                });
            } else
                this.setState({
                    loading: false,
                    data: {},
                    details: [],
                });
            return res.ok;
        });
    }

    componentWillUnmount() {
        this.ismounted = false;
    }

    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };

    onSubmit = () => {
        const {rowVersion} = this.state.data;
        const data = this.state.details.map(item => item.workItemId);
        this.setState({
            loading: true
        });
        return this.props.onClickSubmit({
            assistItems: data,
            rowVersion
        }).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
            return success;
        });
    }


    onClickAdd = () => {
        this.setState({
            hasOperat: true,
            showPanel: true,
        });
    }

    onDelete = e => {
        const {id} = e.target.dataset;
        const details = this.state.details.filter(item => item.workItemId !== id);
        this.setState({
            hasOperat: true,
            details
        });
    }

    onDeleteAll = () => {
        this.setState({
            hasOperat: true,
            details: []
        });
    }

    onSelect = data => {
        const newData = data.map(item => ({
            workItemId: item.id,
            workItemCode: item.code,
            workItemName: item.name,
            laborHour: item.laborHour
        }));
        this.setState({
            showPanel: false,
            details: [...this.state.details, ...newData]
        });
    }

    render() {
        const currentSelectRowKeys = this.state.details.map(item => item.workItemId);
        const assistColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'assistEdit.assistColumns.workItemCode',
                    defaultMessage: '上级工位编号'
                }),
                dataIndex: 'workItemCode',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'assistEdit.assistColumns.workItemName',
                    defaultMessage: '上级工位名称'
                }),
                dataIndex: 'workItemName',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'assistEdit.assistColumns.laborHour',
                    defaultMessage: '上级工位工时'
                }),
                dataIndex: 'laborHour',
            },

            {
                title: this.state.details.length ? (
                    <WrappedPopconfirm
                        id="delete"
                        title={this.props.intl.formatMessage({
                            id: 'assistEdit.popconfirm.message',
                            defaultMessage: '是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'assistEdit.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'assistEdit.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onDeleteAll}>
                        <a>
                            {this.props.intl.formatMessage({
                                id: 'assistEdit.deleteAll',
                                defaultMessage: '清空'
                            })}
                        </a>
                    </WrappedPopconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'assistEdit.deleteAll',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'action',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: (text, record) => <a onClick={this.onDelete} key="delete" data-id={record.workItemId}>
                    {this.props.intl.formatMessage({
                        id: 'assistEdit.delete',
                        defaultMessage: '删除'
                    })}
                </a>
            }
        ];
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'assistEdit.claimModal.title',
                        defaultMessage: '上级工位查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <AssistSelectPanel
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.onSelect} />
                </Modal>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={this.props.intl.formatMessage({
                            id: 'assistEdit.order.title',
                            defaultMessage: '工位信息'
                        })}>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'assistEdit.info.code',
                                    defaultMessage: '工位编号'
                                })}>
                                {this.state.data.code}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'assistEdit.info.name',
                                    defaultMessage: '工位名称'
                                })}>
                                {this.state.data.name}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'assistEdit.info.productCategoryCode',
                                    defaultMessage: '车型编号'
                                })}>
                                {this.state.data.productCategoryCode}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'assistEdit.info.productCategoryName',
                                    defaultMessage: '车型名称'
                                })}>
                                {this.state.data.productCategoryName}
                            </Description>
                            <Description
                                term={this.props.intl.formatMessage({
                                    id: 'assistEdit.info.laborHour',
                                    defaultMessage: '工时'
                                })}>
                                {this.state.data.laborHour}
                            </Description>
                        </DescriptionList>
                        <DescriptionList col={1} size="large">
                            <Description term={this.props.intl.formatMessage({
                                id: 'assistEdit.info.remark',
                                defaultMessage: '备注'
                            })}>
                                {this.state.data.remark}
                            </Description>
                        </DescriptionList>
                    </Card>
                    <Card
                        extra={<Button key="add" onClick={this.onClickAdd} size="small">
                            {this.props.intl.formatMessage({
                                id: 'assistEdit.btn.add',
                                defaultMessage: '新增'
                            })}
                        </Button>}
                        title={this.props.intl.formatMessage({
                            id: 'assistEdit.assistItems.title',
                            defaultMessage: '上级工位清单'
                        })}>
                        <Table className="white-space-nowrap" rowKey="workItemId" columns={assistColumns} pagination={false} dataSource={this.state.details} {...TABLE} />
                    </Card>
                    {this.props.submitable && (
                        <Card type="inner">
                            <Row>
                                <Col className="col-align-right">
                                    <Button
                                        key="submit"
                                        loading={this.state.loading}
                                        onClick={this.onSubmit}
                                        type="primary">
                                        {this.props.intl.formatMessage({
                                            id: 'assistEdit.btn.submit',
                                            defaultMessage: '保存'
                                        })}
                                    </Button>
                                </Col>
                            </Row>
                        </Card>
                    )}
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Detail.propTypes = {
    id: PropTypes.string,
    init: PropTypes.func,
    intl: PropTypes.object,
    permissions: PropTypes.array,
    onCancel: PropTypes.func,
    onClickSubmit: PropTypes.func,
    onUmount: PropTypes.func
};
import {connect} from 'react-redux';
import {
    getDetail,
    tableSearch,
    onClickUpdateAssist,
} from './actions';
const EMPTY_ARRAY = [];
import {createSelector} from 'reselect';
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        return data.includes(PERMISSION.setAssist) && options.includes(PERMISSION.setAssist);
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.goBack();
    },
    onClickSubmit: data => dispatch(onClickUpdateAssist(ownProps.id, data)).then(success => {
        if(success) {
            dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            ownProps.history.goBack();
        }
        return success;
    }),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Detail));
